/**
 * 操作链表的
 */

class Node {
    constructor(data) {
        this.data = data || null;
        this.prev = null;
        this.next = null;
    }
}

class MyLinkedList {
    constructor() {
        this.head = undefined;
        this.last = undefined;
        this.size = 0;
    }
    /**
     * 链表插入元素
     * @param data 插入的元素
     * @param index 插入的位置
     */
    insert(data, index) {
        let insertedNode = new Node(data);

        if (index < 0 || index > this.size) {
            throw Error('超出了链表的实际元素范围');
        }

        if (this.size === 0) {
            // 空链表
            this.head = insertedNode;
            this.last = insertedNode;
        } else if (index === 0) {
            // 插入头部
            insertedNode.next = this.head;
            this.head = insertedNode;
        } else if (index === this.size) {
            // 插入尾部
            this.last.next = insertedNode;
            this.last = insertedNode;
        } else {
            // 插入中间
            let prevNode = this.get(index - 1);
            insertedNode.next = prevNode.next;
            prevNode.next = insertedNode;
        }
        this.size++;
    }
    /**
     * 链表删除元素
     * @param index 删除元素的位置
     */
    remove(index) {
        if (index < 0 || index > this.size) {
            throw Error('超出链表节点的实际范围');
        }
        let removeNode = null;
        if (index === 0) {
            // 删除头部节点
            removeNode = this.head;
            this.head = this.head.next;
        } else if (index === this.size - 1) {
            // 删除尾部节点
            let prevNode = this.get(index - 1);
            removeNode = prevNode.next;
            prevNode.next = null;
            this.last = prevNode;
        } else {
            // 删除中间节点
            let prevNode = this.get(index - 1);
            let nextNode = prevNode.next.next;
            removeNode = prevNode.next();
            prevNode.next = nextNode;
        }
        this.size--;
        return removeNode;
    }
    /**
     * 链表查找元素
     * @param index 链表查找的位置
     */
    get(index) {
        if (index < 0 || index >= this.size) {
            throw Error('超出链表的实际节点范围');
        }
        let temp = this.head;
        for (let i = 0; i < index; i++) {
            temp = temp.next;
        }
        return temp;
    }
    /**
     * 输出链表
     */
    output() {
        let temp = this.head;
        console.log(this.head, this.last);
        while (temp != null) {
            console.log(temp.data);
            temp = temp.next;
        }
    }
    static main(args) {
        let myLinkedList = new MyLinkedList();

        myLinkedList.insert(0, 3);
        myLinkedList.insert(0, 4);
        myLinkedList.insert(2, 9);
        myLinkedList.insert(3, 5);
        myLinkedList.insert(1, 6);
        myLinkedList.remove(0);
        myLinkedList.output();
    }
}

MyLinkedList.main()

